// 用户信息store
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 定义状态
  const username = ref('')
  const userId = ref('')
  const isLoggedIn = ref(false)
  const avatar = ref('')
  const role = ref<number>(0) // 0=普通用户，3=管理员
  const isUserInfoLoaded = ref(false) // 标记用户信息是否已加载

  // 设置用户名
  const setUsername = (name: string, id?: string, adminOrRole?: boolean | number) => {
    username.value = name
    if (id) {
      userId.value = id
    } else if (!userId.value) {
      // 如果没有提供ID且当前没有ID，生成一个随机ID
      userId.value = Math.floor(Math.random() * 9000000000 + 1000000000).toString()
    }
    // 兼容旧参数：既支持布尔 isAdmin，也支持数值 role
    if (adminOrRole !== undefined) {
      if (typeof adminOrRole === 'number') {
        role.value = adminOrRole
      } else {
        role.value = adminOrRole ? 3 : 0
      }
    }
    isLoggedIn.value = true
  }

  const setAvatar = (url: string) => {
    // 验证头像URL的有效性
    if (url && typeof url === 'string' && url.trim() !== '') {
      avatar.value = url.trim()
    } else {
      avatar.value = ''
    }
  }

  // 设置角色
  const setRole = (newRole: number) => {
    role.value = newRole
  }

  // 清除用户信息（登出时使用）
  const clearUser = () => {
    username.value = ''
    userId.value = ''
    isLoggedIn.value = false
    role.value = 0
    isUserInfoLoaded.value = false
  }
  
  // 衍生：管理员判定（兼容现有组件引用 userStore.isAdmin）
  const isAdmin = computed(() => role.value === 3)

  // 设置用户信息加载状态
  const setUserInfoLoaded = (loaded: boolean) => {
    isUserInfoLoaded.value = loaded
  }

  return {
    username,
    userId,
    isLoggedIn,
    avatar,
    role,
    isAdmin,
    isUserInfoLoaded,
    setUsername,
    setUserInfoLoaded,
    setAvatar,
    setRole,
    clearUser
  }
}, {
  persist: true // 持久化存储用户信息
})
